﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using ST.Core;
using ST.Core.Util;

namespace ST.ModelVM.ProtocolDefine
{
    public class ProtocolGDSJVM : IntModel
    {
        public string Name { get; set; } = string.Empty;
        public byte Gnm { get; set; }
        public UInt16 StartAddress { get; set; }

        public UInt16 EndAddress { get; set; }
        public bool BitData { get; set; }
        public UInt16 ReqNum { get; set; }



        public List<ProtocolGDSJRowVM> Data { get; set; } = new List<ProtocolGDSJRowVM>();

        public List<PropValue> PropValue { get; set; } = new List<PropValue>();

        [JsonIgnore]
        public byte[] Bytes { get; set; } = new byte[1];

        public void CreateBytes()
        {
            var total = 0;

            for (var i = 0; i < Data.Count; i++)
            {
                var mPropValue = PropValue[i];
                var o = Data[i];
                mPropValue.DataType = o.DataType;

                switch (o.DataType)
                {
                    case "Bit":
                    case "Byte":
                        mPropValue.Index = total;
                        total++;
                        break;
                    case "UInt16":
                        mPropValue.Index = total;
                        total += 2;
                        break;
                    case "Int":
                        mPropValue.Index = total;
                        total += 4;
                        break;
                    case "Float":

                        mPropValue.Index = total;
                        total += 4;
                        break;
                    default:
                        break;

                }
            }
            this.Bytes = new byte[total];
            this.EndAddress = Convert.ToUInt16(this.StartAddress + total);
            if (!this.BitData)
            {
                this.EndAddress = Convert.ToUInt16(this.StartAddress + total/2);
            }
            for (var i = 0; i < PropValue.Count; i++)
            {
                var mPropValue = PropValue[i];
                ByteUtil.WriteModbusData(this.Bytes, mPropValue.DataType, mPropValue.NumValue.ToString(), mPropValue.Index);
            }
        }
    }
}
